package cn.jslancer.webx.response;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.util.Map;

/**
 * @author zhuangchao
 * @date 2019/12/27 11:13
 */
public class WebxResponse implements ServerResponse {


    private ChannelHandlerContext ctx;

    private String content;

    private String contentType;

    private int contentLength;

    private Map<String, String> headers;

    public WebxResponse(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }

    @Override
    public Map<String, String> getHeaders() {
        return headers;
    }

    @Override
    public void setHeaders(Map<String, String> headers) {
        this.headers = headers;
    }

    @Override
    public void setContent(String content) {
        this.content = content;
        this.contentLength = content.length();
    }

    @Override
    public String getContent() {
        return this.content;
    }

    @Override
    public int getContentLength() {
        return this.contentLength;
    }

    @Override
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    @Override
    public void write() {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                Unpooled.wrappedBuffer(content.getBytes()));

        response.headers().set(HttpHeaderNames.CONTENT_TYPE.toString(), contentType);
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH.toString(), contentLength);

        ctx.writeAndFlush(response);
    }
}
